 <template>
    <div>
      <header-bar :title="imgsPreviewTitle" title-color="#fff" :type="88" :interceptReturn="true" @return="closeImgsPreview" v-show="imgsPreviewShow">
        <img class="header_delete_icon" slot="right" src="~@/assets/imgs/common/delete_icon.png" @click="deleteImg2">
      </header-bar>
      <cube-upload
        ref="upload"
        v-model="files"
        :action="action"
        :simultaneous-uploads="10"
        :max="10"
        :process-file="processFile"
        @files-added="addedHandler"
        @file-submitted="fileSubmitted" 
        @file-error="errHandler"
        @file-success="successHandler"
      >
        <div class="img_list">
          <cube-upload-file v-for="(file, i) in files" :file="file" :key="i">
            <div class="img_item_box">
              <img class="delete_icon" src="~@/assets/imgs/common/close_icon.png" @click="deleteImg(i)" v-if="sourceFrom !='aishangjie'">
              <div class="inner_box" @click="showImagePreview(i)" :style="{'background-image': 'url('+ file.url +')'}">
                 <!-- <img class="img_item" :src="file.url"> -->
              </div>
              <div class="main_img_tips" v-if="i == 0">主图</div>
            </div>
          </cube-upload-file>
          <!-- 来自爱上街的不需要再上传图片 -->
          <cube-upload-btn :multiple="true" v-show="files.length < 10 && sourceFrom !='aishangjie'">
            <div class="img_item_box">
                <img class="img_item bdr16" src="~@/assets/imgs/common/upload_icon.png">
            </div>
          </cube-upload-btn>
        </div>
      </cube-upload>
      <div class="footer_bar fix_iphonex" v-show="imgsPreviewShow && initialIndex != 0">
        <div class="set_mian_btn" @click="changeMainImg">设为主图</div>
      </div>
    </div>
</template>

<script>
import HeaderBar from "@/components/header.vue"
import {mapState,mapActions} from 'vuex';
import { Upload } from 'cube-ui';
import { baseURL } from '@/api/request';
import compress from '@/assets/js/image';
import native from '@/libs/native/index';
let token = localStorage.getItem('token') || 'APP_TOKEN_98c424be-24a6-4983-bbc8-d61d673674d5'
export default {
  props: {
    compressParams:{
        type:Object,
        default(){
            return {
              width: 750,
              height: 2000,
              quality: 0.7
            }
        }
    },
    imgList:{
        type:Array,
        default(){
            return [];
        }
    },
    headerShow:{
      type:Boolean,
      default:true
    }
  },
  components:{
    HeaderBar,
    cubeUpload:Upload,
    cubeUploadFile:Upload.File,
    cubeUploadBtn:Upload.Btn,
  },
  data() {
    return {
      action: {
        // target: baseURL + '/app/h5/file/upload',
        target: baseURL + '/app/h5/file/compressUploadImage',
        prop: 'file',
        headers:{
           'token':token
        }
      },
      files:[],
      imgs:[],
      initialIndex:0,
      sourceFrom:'',
      // compressFlag:true,
      imgsPreview:null,
      imgsPreviewShow:false,
      imgsPreviewTitle:""
    }
  },

  created() {
    this.sourceFrom = this.$route.query.from || '';
    // let ua = navigator.userAgent.toLowerCase();
    // if(ua.indexOf("like mac os x") > 0){
    //   let reg = /os [\d._]*/gi ;
    //   let verinfo = ua.match(reg) ;
    //   let version = (verinfo+"").replace(/[^0-9|_.]/ig,"").replace(/_/ig,".");
    //   // if(version.split('.')[0]<11){
    //     this.compressFlag = false;
    //   // }
    // }
    this.initFiles()
  },
 
  methods: {
    ...mapActions(['toggleLoading','showMsg','showModal']),
    processFile(file, next) {
      // if(this.compressFlag){
      //   compress(file, {
      //     type:'file',
      //     compress: this.compressParams
      //   }, next);
      // }else{
        next(file);
      // }

    },
    initFiles(){
      let files = []
      this.imgList.forEach((item,index)=>{
        files.push({
          url:item,
          response:{
            data:item
          }
        })
      });
      this.imgs = this.imgList;
      this.files = files;
    },
    fileSubmitted(file) {
    
    },
    addedHandler(files) {
      this.toggleLoading({flag:true});
      for (let k in files) {
        let file = files[k];
        if ( file.type && file.type.indexOf('image') == -1) {
          file.ignore = true;
          this.showMsg({content:'请上传图片文件'});
        };
        if(!file.type && file.type + '' != 'undefined'){
          file.ignore = true;
          this.showMsg({content:'请上传图片文件'});
        }
      }
    },
    
    errHandler(file) {
      this.showMsg({content:'图片上传失败，请重新上传'});
      file && this.$refs.upload.removeFile(file);
      this.toggleLoading({flag:false});
    },
    successHandler(file){
        this.toggleLoading({flag:false});
        if(file.response.code == '9996' || file.response.code == '1003'){
           localStorage.removeItem('token');
           localStorage.removeItem('userInfo');
           native.goLogin();
        };
        if(file.response.code != '0000'){
          this.showMsg({content:file.response.msg});
          file && this.$refs.upload.removeFile(file);
        }else{
           this.emitImgsData();
        }
    },
    deleteImg(index){
      const file = this.files[index];
      file && this.$refs.upload.removeFile(file);
      this.emitImgsData();
    },
    emitImgsData(){
      let imgList = [];
      this.files.forEach(item=>{
        if(item.response && item.response.data){
          imgList.push(item.response.data);
        }
      });
      this.imgs = imgList;
      this.$emit('update:imgList',imgList)
    },

    showImagePreview(index){
      let that = this;
      this.initialIndex = index
      this.imgsPreviewTitle = this.initialIndex + 1 + '/' + this.imgs.length;
      this.emitImgsData();
      const params = {
        $props: {
          imgs: this.imgs,
          initialIndex: 'initialIndex', // 响应式数据的key名
          loop: false,
        },
        $events: {
          change: (i) => {
            // 必须更新 initialIndex
            this.initialIndex = i;
            that.initialIndex = i;
            that.imgsPreviewTitle = i + 1 + '/' + that.imgs.length;
          },

          hide(){
            that.imgsPreviewShow = false;
          }
        }
      };
      let renderFn = (h) => {
        return [h('div', {
          slot: 'footer'
        },'')]
      };
      this.imgsPreviewShow = true;
      this.imgsPreview = this.$createImagePreview({ ...params },renderFn);
      this.imgsPreview.show();
    },

    closeImgsPreview(){
      this.imgsPreview.hide();
    },
    changeMainImg(){
      let index = this.initialIndex;
      let file = this.files[index];
      this.files.splice(index,1);
      this.files.unshift(file);
      this.emitImgsData();
      this.imgsPreview.hide();
    },
    deleteImg2(){
      let index = this.initialIndex;
      this.deleteImg(index);
      this.imgsPreview.hide();
      this.$nextTick(()=>{
        if(this.files.length == 0){
          this.closeImgsPreview();
        }else{
          if(index == 0){
            this.showImagePreview(index);
          }else{
            this.showImagePreview(index-1);
          }
        }
      })
     
    }
  }
}
</script>

<style lang="less" scoped>
.img_list{
  display: flex;
  flex-wrap: wrap;
  .img_item_box{
    position: relative;
    width: 1.4rem;
    height: 1.4rem;
    margin-right: 0.32rem;
    margin-bottom:0.32rem;
    .delete_icon{
      position: absolute;
      width: 0.36rem;
      height: 0.36rem;
      right: -0.18rem;
      top:-0.18rem;
      z-index: 10;
    }
    .inner_box{
      width: 1.4rem;
      height: 1.4rem;
      position: relative;
      overflow: hidden;
      border-radius: 0.16rem;
      background-position: center center;
      background-size: cover;
      background-repeat: no-repeat;
      // .img_item{
      //   position: absolute;
      //   top:50%;
      //   left: 50%;
      //   transform: translate(-50%,-50%);
      // }
    }
    .bdr16{
      border-radius: 0.16rem;
    }
    .img_item{
      // width: 1.4rem;
      width: auto;
      height: 1.4rem;
    }
    .main_img_tips{
      position: absolute;
      background-color: #14C877;
      color: #fff;
      opacity: 0.8;
      width: 100%;
      font-size: 0.24rem;
      line-height: 0.36rem;
      text-align: center;
      left: 0;
      bottom: 0;
      border-radius: 0 0 0.16rem 0.16rem;
    }
  }
}
.header_delete_icon{
  width: 0.4rem;
  height: 0.4rem;
}
.footer_bar{
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding-top: 0.2rem;
  background-color: #25262d;
  display: flex;
  justify-content: center;
  z-index: 101;
  .set_mian_btn{
    padding:0.1rem 0.2rem;
    color: #fff;
    border:0.02rem solid #fff;
    border-radius: 0.04rem;
    margin-bottom: 0.4rem;
  }

}
</style>
